import { useRef, useState } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Popconfirm, Table } from 'antd';
import dayjs from 'dayjs';
import { omit } from 'lodash-es';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import {
  proDataAgentPriceDelete,
  proDataAgentPricePage
} from '@/services/bizApi/yaojixiandanjiajiekou';

import Edit, { EditRef } from './edit';
import ImportModal, { ImportRef } from './import';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProDataAgentPriceEntity & {
  rq?: [Date, Date];
};

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();
  const [weekRange, setWeekRange] = useState({
    startDate: null,
    endDate: null
  });
  const importModalRef = useRef<ImportRef>(null);

  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      let query = {
        ...formData,
        ...id,
        startDate: weekRange.startDate
          ? dayjs(weekRange.startDate).format('YYYY-MM-DD')
          : undefined,
        endDate: weekRange.endDate ? dayjs(weekRange.endDate).format('YYYY-MM-DD') : undefined,
        page: current,
        size: pageSize
      };

      query = omit(query, ['rq']);
      const res = await proDataAgentPricePage(query);

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    setWeekRange({
      startDate: null,
      endDate: null
    });
    table.search.reset();
  };

  //药剂合计用量
  const handleTotal = (data: BizObject[]) => {
    let total = 0;
    const dataNew = omit(data, ['id', 'index', 'startDate', 'endDate', 'yjyl']);
    console.log('dataNew:', dataNew);

    Object.values(dataNew).forEach((value) => {
      total += Number(value as number);
    });

    return total.toFixed(3);
  };

  // const handleImport = useRequest(
  //   async () => {
  //     const formData = new FormData();
  //     formData.append('file', fileList.current[0].originFileObj as File);

  //     await proDataSewageImport({} as ArgumentsType<typeof proDataSewageImport>[0], {
  //       method: 'POST',
  //       headers: {
  //         'Content-Type': 'multipart/form-data'
  //       },
  //       data: formData,
  //       timeout: 60000
  //     });

  //     store.app?.message.success('导入成功');
  //     table.search.submit();
  //   },
  //   {
  //     manual: true
  //   }
  // );

  const handleWeekSelect = (date: any) => {
    if (!date) {
      setWeekRange({ startDate: null, endDate: null });
      return;
    }

    // 计算周开始日期（周一）
    const startDate = date.startOf('week');
    // 计算周结束日期（周日）
    const endDate = date.endOf('week');
    // 获取周数
    console.log(date.week());
    setWeekRange({
      startDate: startDate.format('YYYY-MM-DD'),
      endDate: endDate.format('YYYY-MM-DD')
    });

    setTimeout(() => {
      table.search.submit();
    }, 500);
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  importModalRef.current?.open({
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                导入
              </Button>
            )}
            {permission.check() && (
              <Button
                onClick={() => {
                  edit.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                新增
              </Button>
            )}
          </>
        }
      >
        <div style={{ display: 'flex' }}>
          <div>
            <Filter.Item name="rq">
              <DatePicker
                picker="week"
                allowClear={false}
                format="YYYY-w周"
                onChange={handleWeekSelect}
                placeholder={'请选择周'}
              />
            </Filter.Item>
          </div>
          <div style={{ margin: ' 0 20px', lineHeight: '32px' }}>
            周日期: {weekRange?.startDate} - {weekRange?.endDate}
          </div>
        </div>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}
      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, row, index) => index + 1
          },
          {
            title: '开始日期',
            dataIndex: 'startDate',
            render: (text, row) => <div>{dayjs(text).format('YYYY-MM-DD')}</div>
          },
          {
            title: '结束日期',
            dataIndex: 'endDate',
            render: (text, row) => <div>{dayjs(text).format('YYYY-MM-DD')}</div>
          },
          {
            title: '药剂用量(合计)',
            dataIndex: 'yjyl',
            render: (text, row) => (
              <div style={{ fontWeight: 'bold' }}>{handleTotal(row as BizObject[])}</div>
            )
          },
          { title: '植物除臭药剂', dataIndex: 'zwccyj' },
          { title: '次氯酸钠', dataIndex: 'clsd' },
          { title: '等效碳源', dataIndex: 'dxtr' },
          { title: '复合型碳源', dataIndex: 'fhxtr' },
          { title: '葡萄糖', dataIndex: 'ptj' },
          { title: '聚氯化铝', dataIndex: 'jlhhl' },
          { title: '七水硫酸亚铁', dataIndex: 'qslsytt' },
          { title: '除磷剂', dataIndex: 'cpj' },
          { title: '碱', dataIndex: 'j' },
          { title: '片碱', dataIndex: 'pj' },
          { title: '液碱', dataIndex: 'yj' },
          { title: '稀硫酸', dataIndex: 'xls' },
          { title: '盐酸', dataIndex: 'ys' },
          { title: '阳离子聚丙烯酰胺(气浮)', dataIndex: 'ylzblxyamqf' },
          { title: '阳离子聚丙烯酰胺(脱泥)', dataIndex: 'ylzblxyamdn' },
          { title: '双氧水', dataIndex: 'dyy' },
          { title: '消泡剂', dataIndex: 'xpj' },
          { title: '柠檬酸', dataIndex: 'mlss' },
          { title: '膜清洗剂', dataIndex: 'mqxj' },
          { title: '纳滤阻垢剂', dataIndex: 'nlfzgj' },
          { title: '膜清洗剂(酸性)', dataIndex: 'mqxjsx' },
          { title: '膜清洗剂(碱性)', dataIndex: 'mqxjjx' },
          { title: '洛碛渗滤液非氧化杀菌剂', dataIndex: 'lqslfyyxj' },
          { title: '氯化铁液体', dataIndex: 'lhtyt' },
          { title: '水费(吨)', dataIndex: 'sf' },
          { title: '餐厨污水厂(水费)', dataIndex: 'sfCcwsc' },
          { title: '洛碛渗滤液污水厂(水费)', dataIndex: 'sfLqslfywsc' },
          { title: '黑石子污水厂(水费)', dataIndex: 'sfHszwsc' },
          { title: '界石污水厂(水费)', dataIndex: 'sfJswsc' },
          { title: '走马污水厂(水费)', dataIndex: 'sfZmwsc' },
          { title: '夏家坝污水厂(水费)', dataIndex: 'sfXjbwsc' },
          { title: '电费(度)', dataIndex: 'df' },
          { title: '餐厨污水厂(电费)', dataIndex: 'dfCcwsc' },
          { title: '洛碛渗滤液污水厂(电费)', dataIndex: 'dfLqslfywsc' },
          { title: '黑石子污水厂(电费)', dataIndex: 'dfHszwsc' },
          { title: '界石污水厂(电费)', dataIndex: 'dfJswsc' },
          { title: '走马污水厂(电费)', dataIndex: 'dfZmwsc' },
          { title: '夏家坝污水厂(电费)', dataIndex: 'dfXjbwsc' },
          { title: '原水厂(电费)', dataIndex: 'dfYsc' },
          { title: '污泥外运', dataIndex: 'wnwy' },
          { title: '污泥填埋', dataIndex: 'wntm' },
          { title: '污泥热水解', dataIndex: 'wnrsj' },
          { title: '取水费', dataIndex: 'qsf' },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              function equDefectAcceptanceSubmit(arg0: { id: string }) {
                throw new Error('Function not implemented.');
              }

              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      onClick={() =>
                        edit.current!.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        })
                      }
                    >
                      编辑
                    </Text>
                  )}
                  {permission.check() && (
                    <Popconfirm
                      title={`确定删除该条数据吗？`}
                      onConfirm={async () => {
                        const res = await proDataAgentPriceDelete({
                          id: row.id as unknown as string
                        });

                        store.app?.message.success('删除成功');
                        table.refresh();
                      }}
                    >
                      <Text>删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}
      <Edit ref={edit} />
      <ImportModal ref={importModalRef} />
    </>
  );
};

export default Page;
